package com.jblv.frame.web.filter;

import com.alibaba.dubbo.config.annotation.Reference;
import com.jblv.frame.common.enums.ExceptionEnum;
import com.jblv.frame.common.message.Result;
import com.jblv.frame.common.utils.ClientUtils;
import com.jblv.frame.common.utils.GsonUtils;
import com.jblv.frame.common.utils.SpringContextUtils;
import com.jblv.frame.user.api.bll.ISysLogBLL;
import com.jblv.frame.user.api.entity.SysLog;
import com.jblv.frame.user.api.service.ISysLogService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author happyonion.yangtao
 * @version 1.0
 * @title ApiAccessFilter
 * @projectName jblv-frame
 * @packageName com.jblv.web.filter
 * @description ApiAccessFilter-
 * @date Create at 2020/5/8 15:23
 * @since jdk1.8
 */
@WebFilter(urlPatterns = {"/v1/api/*"},filterName = "apiAccessFilter")
@Order(1)////指定过滤器的执行顺序,值越大越靠后执行
public class ApiAccessFilter  implements Filter {
    private static final Logger logger = LoggerFactory.getLogger(ApiAccessFilter.class);

    @Reference(check = false)
    ISysLogBLL iSysLogBLL;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("ApiAccessFilter init");
    }

    @Override
    public void destroy() {
        System.out.println("ApiAccessFilter destory");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 返回JSON字符串
        String responseJson = "";

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

//        String origin = request.getHeader("Origin");
//        if(origin == null) {
//            origin = request.getHeader("Referer");
//        }
//        //这里不能写*，*代表接受所有域名访问，如写*则下面一行代码无效。谨记
//        response.setHeader("Access-Control-Allow-Origin", origin);
//        //true代表允许携带cookie
//        response.setHeader("Access-Control-Allow-Credentials", "true");

        String uri =  request.getRequestURI();
        logger.info("apiAccessFilter-uri-[{}]",uri);


        FrameHttpServletRequestWrapper requestWrapper = new FrameHttpServletRequestWrapper(request);
        FrameHttpServletResponseWrapper responseWrapper = new FrameHttpServletResponseWrapper(response);

        // body请求参数
        String body = requestWrapper.getBody();
        logger.info("apiAccessFilter-bodyStr-[{}]",body);

        if(false){
            responseError(response, ExceptionEnum.REQUEST_ERROR.getCode(),ExceptionEnum.REQUEST_ERROR.getMessage());
            return;
        }

        try {
            filterChain.doFilter(requestWrapper, responseWrapper);
        }catch (Exception e){
            logger.error(e.getMessage());
        }

        byte[] content = responseWrapper.getContent();

        responseJson = new String(content, StandardCharsets.UTF_8);

        //JsonObject jsonObject = GsonUtils.getJsonObject(responseJson);
        //这里可以后期增加返回日志处理
        String ip = ClientUtils.getIpAddress(request);
        String operation = request.getQueryString();
        String method = request.getMethod();
        if(iSysLogBLL==null){
            logger.error("isyslogbll is null");
        }
        iSysLogBLL.saveLog("system",operation,method,body,responseJson,ip);

        logger.info("apiAccessFilter-responseJson-[{}]",responseJson);
        servletResponse.getWriter().println(responseJson);
    }


    private String responseError(HttpServletResponse response, int code, String msg) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        Result<String> result = new Result<>();

        result.setMessage(msg);
        result.setCode(code);
        result.setStatus(0);

        String responseJson = GsonUtils.getJsonStr(result);
        try {
            response.getWriter().println(responseJson);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return GsonUtils.getJsonStr(responseJson);
    }
}
